<template>
  <div class="reset-pwd q-gutter-y-sm q-px-lg">
    <div class="warning-tips text-grey-7 text-weight-medium row items-center no-wrap q-my-lg">
      <q-icon class="map-warning-tips-icon" name="mdi-information-variant" size="1.25rem"></q-icon>
      <div>{{ $t('ResetPwdTip1') }}</div>
    </div>
    <!-- 新密码 -->
    <q-input ref="nameInput" v-model="formInfo.password" :loading="loading" :placeholder="`${$t('Password')}`"
             :readonly="loading" :rules="[val => val && val.length > 0 || `${$t('PleaseInput')} ${$t('Password')}`]"
             dense lazy-rules outlined type="password" @keydown.enter="setKeyCode" @keyup.enter="login('Input')">
      <template v-slot:prepend>
        <q-icon name="lock" />
      </template>
    </q-input>
    <!-- 确认密码 -->
    <q-input ref="codeInput" v-model="formInfo.newPassword" :loading="loading" :placeholder="`${$t('ConfirmPass')}`"
             :readonly="loading" :rules="[val => pwdVali(val)]" dense lazy-rules outlined type="password"
             @keydown.enter="setKeyCode" @keyup.enter="login('Code')">
      <template v-slot:prepend>
        <q-icon name="lock" />
      </template>
    </q-input>

    <q-btn :loading="loading" class="full-width q-mb-xl bg-login-btn text-subtitle1 text-weight-bold" flat rounded
           text-color="white" @click="login">
      {{ `${$t('ResetPwd')}` }}
    </q-btn>
  </div>
</template>

<script setup>

import { postAPI } from 'src/api'
import { i18n } from 'boot/i18n'
import { inject, ref } from 'vue'

const props = defineProps({
  step: Number,
  username: String,
  captchaKey: String
})

const TENANT_ID = inject('TENANT_ID')
const emits = defineEmits(['update:step'])

const keyCode = ref(0)
const loading = ref(false)
const codeInput = ref(null)
const nameInput = ref(null)
const formInfo = ref({ captchType: 'MAIL', tenantId: TENANT_ID })

const pwdVali = val => {
  if (!val) return `${i18n.t('AgainPwd')}`
  if (val === formInfo.value.password) return true
  return `${i18n.t('ErrorPwd')}`
}

const setKeyCode = e => (keyCode.value = e.keyCode)

const login = keyType => {
  if (keyCode.value === 229) return // 中文输入法输入中文情况下 keydown.enter事件键值为229
  if (keyType === 'Input' && !nameInput.value.validate()) return nameInput.value.focus()
  if (keyType === 'Code' && !codeInput.value.validate()) return codeInput.value.focus()

  if (!nameInput.value.validate()) return nameInput.value.focus()
  if (!codeInput.value.validate()) return codeInput.value.focus()

  codeInput.value.blur()
  nameInput.value.blur()

  loading.value = !loading.value
  formInfo.value.captchaKey = props.captchaKey

  postAPI('/auth/api/captcha/setPasswordByCode', formInfo.value, () => {
    emits('update:step', 4)
    loading.value = !loading.value
  }, () => {
    loading.value = !loading.value
  })
}

</script>